<?php
/* Desc : Mysql Object Wrapper
 * Author : HoonJoon-Park (a.k.a Maya)
 */
class DiyModel
{
  var $model;
  var $id_col_name;
  var $id=0;
  
  function DiyModel($model, $id_col_name = "id") {
    $ini = parse_ini_file(ROOT_DIR . '.diycity.ini');
    $conn = mysql_connect('localhost', 'diycity', $ini['mysql_password']); 
    if (!$conn)
      {
	die('Connect Error (' . mysql_error(). ')');
      }
    mysql_select_db("diycity",$conn);

    $this->model = $model;
    $this->id_col_name = $id_col_name;
  }

  function reset() {
    $this->query("DELETE FROM " . $this->model);
    $this->query("ALTER TABLE " . $this->model . " AUTO_INCREMENT=1");
  }

  function getError() {
    return mysql_error();
  }

  function query($query) {
    return mysql_query($query);
  }
  
  /* Save a field : UPDATE */
  function saveField($field_name, $field_value) {
    $query = "UPDATE " . $this->model .
      " SET `{$field_name}`='" . $field_value . "' WHERE `" . $this->id_col_name . "`='" . $this->id . "'";
    if (DEBUG) echo "<span style=\"color:red\">" . $query . "<br /></span>";
    return mysql_query($query);
  }

  function updateAll($fields, $conditions) {
    $query = "UPDATE `" . $this->model . "` " .
      " SET ";

    $cnt=0;
    $total = count($fields);
    foreach($fields as $key => $val) {
      $cnt++;

      $query .= "`{$key}`=\"{$val}\"";
      
      if ($cnt != $total) {
	$query .= ",";
      }
    }
    $cond = array("conditions" => $conditions);
    $this->query($query . $this->buildQuery("UPDATE", "", $cond));
  }
  
  /* Read a field : SELECT */
  function read($field) {
    $query = "SELECT `$field` FROM " . $this->model . " WHERE `{$this->id_col_name}`='" . $this->id . "'";
    if (DEBUG) echo "<span style=\"color:red\">" . $query . "<br /></span>";

    $res = $this->query($query);

    $row = @mysql_fetch_array($res, MYSQL_NUM);
    return $row[0];
  }

  /* Save data : INSERT */
  function save($data) {
    if (!$data)
      return;
    $query = "INSERT INTO `" . $this->model . '` SET ';

    $cnt = 0;
    $total = count($data);
    foreach($data as $key => $val) {
      $cnt++;

      $query .= "`{$key}`=\"{$val}\"";
      
      if ($cnt != $total) {
	$query .= ",";
      }
    }
    $query .= ';';

    $result = mysql_query($query);
    $this->id = mysql_insert_id();
    return $result; 
  }

  function remove($id=null) {
    $query = "DELETE FROM " . $this->model . " WHERE `{$this->id_col_name}`='" . $id . "'";
    if (DEBUG) echo "<span style=\"color:red\">" . $query . "<br /></span>";
    return $this->query($query);
  }

  function deleteAll($conditions=null) {
    echo $this->buildQuery("DELETE", "", $conditions);
  }
  
  function find($method, $option=null) {
    $result = array();
    $query = $this->buildQuery("SELECT", $method, $option);
    if (DEBUG) echo "<span style=\"color:red\">" . $query . "<br /></span>";

    $source = mysql_query($query);
    if(!$source) {
      echo mysql_error();
    }

    if ($method == 'count') {
      $row = @mysql_fetch_array($source, MYSQL_NUM);
      return $row[0];
    }

    while ($row = @mysql_fetch_array($source, MYSQL_ASSOC)) {
      $result[] = $row;
    }
    
    return $result;
  }

  function condQuery($query, $key, $val, $paren=null) {
    $pattern = '/<=|>=|!=|<|>/';

    preg_match($pattern, $key, $matches, PREG_OFFSET_CAPTURE);

    if (count($matches)) {
      if ($paren)
	$query .= "(`" . trim(substr($key, 0, $matches[0][1])) .  "`". " {$matches[0][0]} " . "'" . $val . "')";
      else
	$query .= "`" . trim(substr($key, 0, $matches[0][1])) .  "`". " {$matches[0][0]} " . "'" . $val . "'";
    } else if(strstr(strtolower($key), "like")) {
      if ($paren) 
	$query .= "({$key} '" . $val . "')"; /* QUERY STRING */
      else
	$query .= "{$key} '" . $val . "'"; /* QUERY STRING */
    } else {
      if ($paren) 
	$query .= "(`{$key}`='" . $val . "')"; /* QUERY STRING */
      else
	$query .= "`{$key}`='" . $val . "'"; /* QUERY STRING */
    }

    return $query;
  }

  function buildQuery($action, $method, $option) {
    if (strtolower($action) == "update")
      $query = "";
    else
      $query = "{$action} ";

    $method = strtolower($method);
    /* FIELDS */
    if (isset($option['fields'])) {
      $fields = $option['fields'];
      $total_cnt = count($fields);
      $cnt=0;
      
      foreach($fields as $key) {
	$cnt++;
	$query .= "{$key}";
	if ($cnt != $total_cnt)
	  $query .= ",";
      }
      $query .= " ";
    } else {
      if ($action != "DELETE") {
	if ($method == 'all') {
	  $query .= "* ";
	} else if ($method == 'count') {
	  $query .= "COUNT(*) ";
	} else {
	  $query .= " ";
	}
      }
    }

    if (strtolower($action) == "update")
      $query .= " ";
    else
      $query .= ("FROM `" . $this->model . "` ");

    /* CONDITIONS(where) */
    if (isset($option['conditions'])) {
      $conditions = $option['conditions'];
      $total_cnt = count($conditions);
      $cnt=0;

      $query .= "WHERE ";
      foreach($conditions as $key => $val) {

	$cnt++;
	$lower_key = strtolower($key);

	if ($lower_key == "or" || $lower_key == "and") {
	  $more_total_cnt = count($val);
	  $more_cnt = 0;
	  $query .= "(";

	  foreach($val as $more_key => $more_val) {
	    $more_cnt++;

	    $query = $this->condQuery($query, $more_key, $more_val, true);
	    //$query .= "(`{$more_key}`='" . $more_val . "')"; /* QUERY STRING */

	    if ($more_cnt != $more_total_cnt) {
	      if ($lower_key == "or")
		$query .= " OR ";
	      else
		$query .= " AND ";
	    }
	  }
	  $query .= ") ";
	} else {
	  $query = $this->condQuery($query, $key, $val);
	  //$query .= "`{$key}`='" . $val . "'"; /* QUERY STRING */

	  if ($cnt != $total_cnt) {
	    $query .= " AND ";
	  }
	}
	$query .= " ";
      }
    }

    
    /* GROUP BY */
    if (isset($option['group'])) {
      $group = $option['group'];
      $group_total_cnt = count($order);
      $group_cnt = 0;

      foreach($group as $group_key => $group_value) {
	$group_cnt++;
	$query .= "GROUP BY `" . $group_value . "` ";	
      }
    }
    
    /* ORDER BY */
    if (isset($option['order'])) {
      $order = $option['order'];
      //       $order_total_cnt = count($order);
      //       $order_cnt = 0;
      //       foreach($order as $order_key => $order_value) {
      // 	$order_cnt++;
      $query .= "ORDER BY " . $order . " ";	
      //       }
    }

    /* LIMIT & PAGE : TODO : PAGE */
    if (isset($option['limit'])) {
      if (isset($option['page'])) {
	$query .= "LIMIT " . $option['page'] . "," . $option['limit'];;
      } else {
	$query .= "LIMIT " . $option['limit'];
      }

    }

    return $query;
  }
}

?>
